package level4.grid_case.astar.test
{
	import astar.AStar;
	import astar.Grid;
	import astar.PathFormula;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.utils.getTimer;

	public class PathFind1 extends Sprite
	{
		private var cellSize:int = 30;
		private var w:int = 800;
		private var h:int = 600;
		//
		private var grid:Grid;
		private var player:Player;
		private var path:Array;
		private var index:int;
		
		public function PathFind1()
		{
			addEventListener(Event.ADDED_TO_STAGE,init);
		}
		private function init(e:Event):void{
			makeGrid();
			makePlayer();
			makeListener();
		}
		private function makeGrid():void{
			graphics.beginFill(0xcccccc,0.5);
			graphics.drawRect(0,0,w,h);
			graphics.endFill();
			var rows:int = h/cellSize;
			var cols:int = w/cellSize;
			//加入网格
			grid = new Grid(cols,rows);
			//绘制网格背景
			trace(rows,cols)
			graphics.lineStyle(1,0x0000ff);
			
			for(var i:int = 0;i<rows;i++){
				for(var j:int= 0;j<cols;j++){
					if(Math.random()*10>6){
						grid.setWalkable(j,i,false);
						//绘制
						graphics.beginFill(0xabcdef,.6);
						graphics.drawRect(j*cellSize,i*cellSize,cellSize,cellSize);
						graphics.endFill();
					}else{
						graphics.drawRect(j*cellSize,i*cellSize,cellSize,cellSize);
					}
				}
			}
		}
		private function makePlayer():void{
			player = new Player();
			player.x = Math.random() * w;
			player.y = Math.random() * h;
			addChild(player);
		}
		private function makeListener():void{
			stage.addEventListener(MouseEvent.CLICK,onClick);
		}
		private function onClick(e:MouseEvent):void{
			var xpos:int = Math.floor(e.localX/cellSize);
			var ypos:int = Math.floor(e.localY/cellSize);
			grid.setEndNode(xpos,ypos);
			xpos = Math.floor(player.x/cellSize);
			ypos = Math.floor(player.y/cellSize);
			grid.setStartNode(xpos,ypos);
			var finder:AStar = new AStar();
				finder.heuristic = PathFormula.DIAGONAL;
			if(finder.findPath(grid)){
				path = finder.path;
				index = 0;
				addEventListener(Event.ENTER_FRAME,enterFrame);
			}
		}
		
		///一下控制角色移动
		private var v:int = 5;
		
		private function enterFrame(e:Event):void{
			var tx:Number = path[index].x * cellSize + cellSize/2;
			var ty:Number = path[index].y * cellSize + cellSize/2;
			var dx:Number = tx - player.x;
			var dy:Number = ty - player.y;
			var dist:Number = Math.sqrt(dx*dx+dy*dy);
			
			var angle:Number = Math.atan2(dy,dx);
			
			if(dist<v){
				index ++;
				if(index >= path.length){
					removeEventListener(Event.ENTER_FRAME,enterFrame);
				}
			}else{
//				player.x += dx * .4;
//				player.y += dy * .4;
				player.x += Math.cos(angle) * v;
				player.y += Math.sin(angle) * v;
			}
		}
	}
}